// pages/details/details.js
const app = getApp()
var wh = require("../../utils/wh.js");
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [{
        id: 1,
        img: '../../img/banner.png'
      },
      {
        id: 2,
        img: '../../img/banner.png'
      },
      {
        id: 3,
        img: '../../img/banner.png'
      },
    ],
    morelists: [],
    index: '1',
    allImg: '',
    modal: false,
    istrue: true, 
    cutdown: {
      'hh': 0,
      'dd': 0,
      'mm': 0,
      'ss': 0
    }, //倒计时
    other_cutdown: {
      'dd': 0,
      'mm': 0,
      'ss': 0
    }, //倒计时
    setintvalid: null,
    notcut: false, //是否结束
    groupInfo: '',
    goodsInfo: '',
    otherlist:'',
    group_id: '',
    ShopDetail: '',
    CollectHave: '',
    likeNum: '',
    ShareCount: '',
    onearth: false,
    pagea: 1,
    page_sizea: 5,
    comments: [],
    user_just: '',
    maskHidden: false, // 海报
    have: true,
    url: ''
  },
  nav() {
    this.setData({
      no_data: 0,
      pagea: 1,
      page_sizea: 5,
      onearth: false,
      comments: [],
      have: true,
    });
    this.good_comments()
    let istrue = this.data.istrue
    this.setData({
      istrue: !istrue
    })
  },
  // 立即参团
  joinGroup(e) {
    let that=this;
    wx.navigateTo({
      url: '../joinGroup/joinGroup?sponsor_id=' + e.currentTarget.dataset.id + '&group_id=' + that.data.group_id + '&group_number=' + that.data.groupInfo.group_number,
    })
  },
  bindchange: function(e) {
    this.setData({
      index: e.detail.current + 1,
    })
  },
  coupon() {
    this.setData({
      modal: true
    })
  },
  colse() {
    this.setData({
      modal: false
    })
  },
  // 获取商品评价列表
  good_comments() {
    let that = this;
    let page_size = this.data.page_sizea,
      no_data = this.data.no_data,
      page = this.data.pagea;
    if (no_data == 0) {
      wh.Post('/api/mall.comment/good_comments', {
        page: page,
        page_num: page_size,
        goods_id: that.data.goodsInfo.goods_id
      }, function (res) {
        console.log('商品评价列表', res)
        let shop = that.data.comments.concat(res.list),
          count = res.list.length;
        if (page_size > count) {
          that.data.no_data = 1;
          if (shop.length > 1) {
            that.setData({
              onearth: true
            })
          }
        }
        that.setData({
          comments: shop
        })
        if (that.data.comments.length == 0) {
          that.setData({
            have: false,
          });
        } else {
          that.setData({
            have: true,
          });
        }
      })
    }
  },
  // 查看是否收藏
  CollectHave(goods_id) {
    var that = this;
    wh.Post('/api/mall.collect/have', {
      target_id: goods_id,
      type: 1
    }, function (res) {
      console.log('是否收藏', res)
      that.setData({
        CollectHave: res
      })
    });
  },
  // 收藏提交
  CollectSubmit() {
    var that = this;
    wh.Post('/api/mall.collect/submit', {
      target_id: that.data.goodsInfo.goods_id,
      type: 1
    }, function (res) {
      that.ColletcTotal(that.data.goodsInfo.goods_id)
      let CollectHave = !that.data.CollectHave;
      that.setData({
        CollectHave: CollectHave
      })
    })
  },
  // 获取收藏喜欢统计
  ColletcTotal(goods_id) {
    var that = this;
    wh.Post('/api/mall.collect/total', {
      target_id: goods_id,
      type: 1
    }, function (res) {
      that.setData({
        likeNum: res
      })
    })
  },
  // 获取店铺分享统计信息
  getShareCount(shop_id) {
    var that = this;
    wh.Post('/api/mall.share/get_count', {
      shop_id: shop_id
    }, function (res) {
      console.log('获取店铺分享统计信息', res)
      that.setData({
        ShareCount: res,
      })
    });
  },
  // 获取商家店铺详情
  getShopDetail(shop_id) {
    var that = this;
    wh.Post('/api/mall.shop/detail', {
      shop_id: shop_id
    }, function (res) {
      console.log('店铺详情', res)
      that.setData({
        ShopDetail: res,
      })
    });
  },
  // 更多经典
  morelists(shop_id) {
    let that = this;
    wh.Post('/api/mall.goods/lists', {
      shop_id: shop_id,
      is_recom: 1,
      is_hot: 1
    }, function (res) {
      that.setData({
        morelists: res
      })
      console.log('更多经典', res)
    })
  },
  // 记录用户访问足迹
  FootMarkRecord(shop_id) {
    wh.Post('/api/mall.footmark/record', {
      shop_id: shop_id,
      target_id: shop_id,
      type: 1
    }, function (res) {

    })
  },
  // 获取拼团详情
  getgroupDetail(group_id) {
    let that = this;
    wh.Post('/api/mall.group/detail', {
      group_id: group_id
    }, function(res) {
      // that.FootMarkRecord(res.group.shop_id)
      that.morelists(res.group.shop_id)
      that.getShareCount(res.group.shop_id)
      that.getShopDetail(res.group.shop_id)
      that.CollectHave(res.goods.goods_id)
      that.ColletcTotal(res.goods.goods_id)
      if (res.goods.goods_info) { 
        WxParse.wxParse('goods_detail', 'html', res.goods.goods_info, that)
      };
      clearInterval(that.setintvalid); //清除倒计时
      let thistime = new Date().getTime(); //判断时间
      let start_time = res.group.start_time + '000'; //精确到毫秒数 
      let end_time = res.group.end_time + '000'; //精确到毫秒数 
      if (thistime <= start_time) { //当前时间小于开始时间 活动未开始
        that.start_bargain(start_time, thistime, end_time);
      } else if (thistime < end_time) { //当前时间小于结束时间 活动进行中
        that.end_bargain(end_time, thistime);
      } else {
        that.setData({
          notcut: true
        }); //活动结束
      } 
      console.log('拼团详情', res)
      that.setData({
        groupInfo: res.group,
        goodsInfo: res.goods,
        group_id: res.group.group_id,
        allImg: res.goods.cover_album.length
      })
    })
  },
  // 获取别人的拼团 
  other(group_id) {
    let that = this;
    wh.Post('/api/mall.group/others?', {
      group_id: group_id,
      page: 1,
      page_num: 3
    }, function(res) {
      for (var i = 0; i < res.length; i++) {
        res[i].count_down = that.timestampToTime(res[i].count_down)
      }
      that.setData({
        otherlist: res,
      })
      console.log('别人的拼团',res)
    })
  },
  //活动未开始
  start_bargain: function(start_time, thistime, end_time) {

    let that = this;
    let cha = start_time - thistime; //开始时间减去现在时间
    that.setData({
      cutdaowbefore: true
    });
    that.setintvalid = setInterval(function() {
      cha -= 1000;
      if (cha <= 0) {
        clearInterval(that.setintvalid);
        cha = 0;
        that.end_bargain(end_time, thistime);
      }
      that.time_meter(cha);
    }, 1000);
  },

  //活动已开始
  end_bargain: function(end_time, thistime) {
    let cha = end_time - thistime;
    let that = this;

    that.setData({
      cutdaowbefore: false
    })

    that.setintvalid = setInterval(function() {
      cha -= 1000;
      if (cha <= 0) {
        clearInterval(that.setintvalid);
        cha = 0;
        that.setData({
          notcut: true
        });
        return;
      }
      that.time_meter(cha)
    }, 1000);
  },
  //时间计算
  time_meter: function(timer) {
    let that = this;
    let dd = parseInt(timer / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
    let hh = parseInt(timer / 1000 / 60 / 60 % 24, 10); //计算剩余的小时数
    let mm = parseInt(timer / 1000 / 60 % 60, 10); //计算剩余的分钟数
    let ss = parseInt(timer / 1000 % 60, 10); //计算剩余的秒数
    mm = that.checkTime(mm);
    ss = that.checkTime(ss);
    let cutdown = {
      'dd': dd,
      'hh': hh,
      'mm': mm,
      'ss': ss
    };
    that.setData({
      cutdown: cutdown
    })
  },
  checkTime: function(i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  },
  //时间戳
  timestampToTime: function (timestamp) {
    var date = new Date(timestamp * 1000),//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      Y = date.getFullYear() + '-',
      M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
      D = date.getDate() + ' ',
      h = date.getHours() + ' : ',
      m = date.getMinutes() + ' : ',
      s = date.getSeconds();
    return h + m + s;
  },
  // 直接购买
  tosubmit(){
    let that = this;
    wh.Post("/api/mall.cart/add", {
      goods_id: that.data.goodsInfo.goods_id,
      buy_num: 1
    }, function (res) {
      wx.navigateTo({
        url: '../submit/submit?cart_id=' + res + '&istype=' + 4,
      })
    })
  },
    // 发起拼团
  open: function () {
    let that = this,
      group_id = that.data.group_id;
      wh.Post('/api/mall.group/open', {
        group_id: group_id
      }, function (res) {
        console.log('开团', res)
        if (res.pay==1) {
          wx.showToast({
            title: '您已经发起过该拼团了',
            icon: 'none',
            duration: 2000,
            complete: function () {
              setTimeout(function () {
                wx.navigateTo({
                  url: '../joinGroup/joinGroup?sponsor_id=' + res.sponsor_id + '&group_id=' + group_id + '&group_number=' + that.data.groupInfo.group_number,
                })
              }, 2000);
            }
          })
        }else{
          let istype = 1;//用来判断是拼团进入支付页面的
          wx.navigateTo({
            url: '../submit/submit?istype=' + istype + '&user_gro_id=' + res.join_id + '&sponsor_id=' + res.sponsor_id + '&group_id=' + group_id + '&group_number=' + that.data.groupInfo.group_number,
          })
        }
      })
  },



  // 记录店铺分享
  RecordShare() {
    let that = this;
    wh.Post("/api/mall.share/record_share", { shop_id: that.data.groupInfo.shop_id }, function (res) {
      that.getShareCount(that.data.groupInfo.shop_id)
    })
  },
  // 某某某刚拼团购买了商品
  user_just(group_id) {
    let that = this;
    wh.Post('/api/mall.group/just', {
      group_id: group_id
    }, function (res) {
      console.log('某某某刚拼团购买了商品', res)
      that.setData({
        user_just: res
      })
    })
  },
  // 获取url
  url() {
    let that = this;
    wx.getExtConfig({
      success: function (res) {
        console.log(2, res)
        let url = res.extConfig.apiurl;
        that.setData({
          url: url
        })
      }
    })
  },
  /** 
 * 生成海报
 */
  createPoster: function () {
    let param = this.data.groupInfo,
      url = this.data.url,
      that = this,
      postUrl = '/api/mall.ajax/page_qrcode',
      tag = '拼团',
      s_url = 'pages/groupDetails/groupDetails?group_id=' + this.data.groupInfo.group_id;
    setTimeout(() => {
      wx.showToast({
        title: '海报生成中...',
        icon: "loading",
      });
      setTimeout(() => {
        wx.hideToast();
      }, 10000)
    }, 0);
    param.title = param.group_title;
    param.goods_desc = param.group_desc;
    param.price = param.group_price;
    param.market_price = param.original_price;
    // 获取小程序码
    wh.Post(postUrl, { s_url: s_url }, function (imgUrl) {
      console.log(imgUrl)
      // 将图片保存到本地
      wx.getImageInfo({
        src: param.group_cover,   //请求的网络图片路径
        success: function (res1) {
          param.path1 = res1.path;
          wx.getImageInfo({
            src: imgUrl,    //请求的网络图片路径
            success: function (res2) {
              param.path2 = res2.path;
              // 开始绘制
              app.startToDraw(param, url, tag, imgUrl);
              that.setData({
                maskHidden: true
              });
              // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
              setTimeout(function () {
                // wx.hideLoading()
                wx.canvasToTempFilePath({
                  canvasId: 'mycanvas',
                  success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    that.setData({
                      imagePath: tempFilePath,
                      canvasHidden: true
                    });
                  },
                  fail: function (res) {
                    console.log(res);
                  }
                });
              }, 200);
            }
          });
        }
      });
    });
  },
  /**
   * 点击保存到相册
   */
  poster_save: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        that.setData({
          maskHidden: false
        });
        wx.showToast({
          title: '图片已保存到相册',
        });
      }
    })
  },
  /**
   * 关闭海报
   */
  close_share: function () {
    this.setData({
      maskHidden: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.url()   
    console.log(options.group_id)
    this.getgroupDetail(options.group_id)
    this.user_just(options.group_id)
    this.other(options.group_id)
    this.setData({
      group_id: options.group_id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    app.app_auth(this)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let no_data = this.data.no_dataa,
      page = this.data.page,
      page_size = this.data.page_sizea;
    if (no_data == 0) {
      this.data.page = page + 1;
      this.good_comments()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    return {
      title: that.data.groupInfo.group_title,
      path: '/pages/groupDetails/groupDetails?group_id=' + that.data.group_id,
      imageUrl: that.data.groupInfo.group_cover,
      success: function (res) {
        that.RecordShare()
        console.log('转发成功')
      }
    }
  }
})